package com.sukumar.android.backit.activity;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.sukumar.android.backit.R;
import com.sukumar.android.backit.bean.BackItSMSDataBean;
import com.sukumar.android.backit.db.BackItDBData.BackItSMSInbox;
import com.sukumar.android.backit.gesture.SimpleGestureFilter;
import com.sukumar.android.backit.gesture.SimpleGestureFilter.SimpleGestureListener;
import com.sukumar.android.backit.service.BackItEmailService;
import com.sukumar.android.backit.service.BackItNotifierService;

public class BackItDbActivity extends Activity implements SimpleGestureListener {
	private ListView list;
	private ArrayList<BackItSMSDataBean> arrBingList = new ArrayList<BackItSMSDataBean>();
	private ArrayList<BackItSMSDataBean> selBingList = new ArrayList<BackItSMSDataBean>();
	private SimpleGestureFilter detector;
	private String view = "";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_layout);
		SharedPreferences sharedP = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		String strViewfromNotif = sharedP.getString("view", "BING");
		view = strViewfromNotif;

		list = (ListView) findViewById(R.id.list);
		refreshListView();
		ArrayAdapter<BackItSMSDataBean> adapter = new ArrayAdapter<BackItSMSDataBean>(
				this, R.layout.bing_list, arrBingList);
		list.setAdapter(adapter);
		list.setItemsCanFocus(false);
		list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		if (arrBingList.size() == 1
				&& arrBingList.get(0).getBingId().equals("-9999")) {
			list.setClickable(false);
			list.setLongClickable(false);
		} else {
			registerForContextMenu(list);
		}
		detector = new SimpleGestureFilter(this, this);

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		MenuInflater inflater = getMenuInflater();
		if (view.equals("BING")) {
			inflater.inflate(R.menu.bing_list_menu, menu);
		} else {
			inflater.inflate(R.menu.alert_list_menu, menu);
		}
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if (item.getTitle().equals("Stop alert")) {
			stopService(new Intent(getApplicationContext(),
					BackItNotifierService.class));
		} else if (item.getTitle().equals("Preferences")) {
			startActivity(new Intent(getApplicationContext(),
					BackItPreferenceActivity.class));
		} else if (item.getTitle().equals("Refresh list")) {
			refreshListView();
		} else if (item.getTitle().equals("Back all")) {
			backAllBings();
			refreshListView();
		} else if (item.getTitle().equals("Delete all")) {
			deleteAllBings();
			refreshListView();
		} else if (item.getTitle().equals("Back all & delete")) {
			backAllBings();
			deleteAllBings();
			refreshListView();
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.list) {
			int selCount = addItemsToSelection();

			if (selCount > 0) {
				menu.setHeaderTitle(R.string.long_click_action);
				String[] menuItems = null;
				if (view.equals("BING")) {
					menuItems = getResources().getStringArray(
							R.array.context_menu_bing);
				} else if (view.equals("ALERT")) {
					menuItems = getResources().getStringArray(
							R.array.context_menu_alert);
				}
				for (int i = (menuItems.length / 2); i < menuItems.length; i++) {
					menu.add(Menu.NONE, i, i, menuItems[i]);
				}

			} else {
				menu.setHeaderTitle(R.string.long_click_action);
				String[] menuItems = null;
				if (view.equals("BING")) {
					menuItems = getResources().getStringArray(
							R.array.context_menu_bing);
				} else if (view.equals("ALERT")) {
					menuItems = getResources().getStringArray(
							R.array.context_menu_alert);
				}
				for (int i = 0; i < (menuItems.length / 2); i++) {
					menu.add(Menu.NONE, i, i, menuItems[i]);
				}

			}
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		int menuItemIndex = item.getItemId();
		BackItSMSDataBean selBingDet = arrBingList.get(info.position);
		if (view.equals("BING")) {
			switch (menuItemIndex) {
			case 0:
				backBing(selBingDet);
				int backDelCnt = deleteBing(selBingDet);
				deleteSMS(selBingDet);
				arrBingList.remove(selBingDet);
				refreshListView();
				Toast.makeText(getApplicationContext(),
						backDelCnt + " message is being backed and deleted.",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				backBing(selBingDet);
				Toast.makeText(getApplicationContext(),
						"The BING is being backed.", Toast.LENGTH_SHORT).show();
				break;
			case 2:
				int deleted = deleteBing(selBingDet);
				deleteSMS(selBingDet);
				arrBingList.remove(selBingDet);
				refreshListView();
				Toast.makeText(getApplicationContext(),
						deleted + " message has been deleted.",
						Toast.LENGTH_SHORT).show();
				break;
			case 3:
				addItemsToSelection();
				backSelectedBing();
				deleteSelected();
				refreshListView();
				break;
			case 4:
				addItemsToSelection();
				backSelectedBing();
				refreshListView();
				break;
			case 5:
				addItemsToSelection();
				deleteSelected();
				refreshListView();
				break;
			}
		} else if (view.equals("ALERT")) {
			switch (menuItemIndex) {
			case 0:
				int deleted = deleteBing(selBingDet);
				deleteSMS(selBingDet);
				arrBingList.remove(selBingDet);
				refreshListView();
				Toast.makeText(getApplicationContext(),
						deleted + " messages have been deleted.",
						Toast.LENGTH_SHORT).show();
				break;
			case 1:
				addItemsToSelection();
				deleteSelected();
				refreshListView();
				break;
			}
		}
		return super.onContextItemSelected(item);
	}

	private void getBingFromDB() {
		String strWhere = BackItSMSInbox.BINGID + " <> \"-8888\" and "
				+ BackItSMSInbox.BINGID + " <> \"-9999\"";
		Cursor c = getContentResolver().query(
				BackItSMSInbox.CONTENT_URI,
				new String[] { BackItSMSInbox._ID, BackItSMSInbox.BINGID,
						BackItSMSInbox.RECEPIENT, BackItSMSInbox.MESSAGE,
						BackItSMSInbox._COUNT, BackItSMSInbox.DATE }, strWhere,
				null, null);
		BackItSMSDataBean smsDataBean = null;
		try {
			if (c != null && c.getCount() > 0) {
				c.moveToFirst();
				do {
					smsDataBean = new BackItSMSDataBean();
					smsDataBean.setId(c.getInt(0));
					smsDataBean.setBingId(c.getString(1));
					smsDataBean.setRecepient(c.getString(2));
					smsDataBean.setMessage(c.getString(3));
					smsDataBean.setCount(c.getInt(4));
					smsDataBean.setDate(c.getString(5));
					arrBingList.add(smsDataBean);
				} while (c.moveToNext());
			}
		} catch (Exception e) {

		} finally {
			c.close();
		}
	}

	private void refreshListView() {
		arrBingList.clear();
		TextView header = (TextView) findViewById(R.id.header);
		TextView footer = (TextView) findViewById(R.id.footer);

		if (view.equals("BING")) {
			getBingFromDB();
			header.setText(getText(R.string.Header1) + " ("
					+ arrBingList.size() + ")");
			footer.setText(R.string.Footer1);
		} else if (view.equals("ALERT")) {
			getAlertFromDB();
			header.setText(getText(R.string.Header2) + " ("
					+ arrBingList.size() + ")");
			footer.setText(R.string.Footer2);
		}
		list.setAdapter(new ArrayAdapter<BackItSMSDataBean>(this,
				R.layout.bing_list, arrBingList));
		if (arrBingList.size() == 1
				&& arrBingList.get(0).getBingId().equals("-9999")) {
			list.setClickable(false);
			list.setLongClickable(false);
			unregisterForContextMenu(list);
		} else {
			registerForContextMenu(list);
		}
	}

	private void sendEmailIntent(BackItSMSDataBean bingDets, String action) {
		final Intent emailIntent = new Intent(
				android.content.Intent.ACTION_SEND);
		emailIntent.setType("plain/text");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
				new String[] { "bingmail-gl@nomura.com" });
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, action + " "
				+ bingDets.getBingId());
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "");
		startActivity(Intent.createChooser(emailIntent, "Send mail..."));
	}

	private void sendMailAuto(BackItSMSDataBean bingDets, String action) {
		Intent mailService = new Intent(getApplicationContext(),
				BackItEmailService.class);
		mailService.putExtra("bingId", bingDets.getBingId());
		mailService.putExtra("action", action);
		startService(mailService);
	}

	private int deleteBing(BackItSMSDataBean bingDetails) {
		int no_of_messages_deleted = 0;
		String strWhere = BackItSMSInbox._ID + " = ?";
		no_of_messages_deleted = getContentResolver().delete(
				BackItSMSInbox.CONTENT_URI, strWhere,
				new String[] { bingDetails.getId() + "" });
		return no_of_messages_deleted;
	}

	private int deleteSMS(BackItSMSDataBean bingDetails) {
		SharedPreferences sharedpref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		boolean delSMS = sharedpref.getBoolean(
				getText(R.string.del_sms_inbox_key).toString(), false);
		int no_of_messages_deleted = 0;
		if (delSMS) {
			String selArgs = null;
			if (bingDetails.getBingId().equals("-8888")) {
				selArgs = bingDetails.getMessage();
			} else {
				selArgs = bingDetails.getBingId();
			}

			if (!selArgs.equals("")) {
				no_of_messages_deleted = this.getContentResolver().delete(
						Uri.parse("content://sms"),
						"body like '%" + selArgs + "%'", null);
			}
		}
		return no_of_messages_deleted;
	}

	private void backBing(BackItSMSDataBean bingDetails) {
		if (view.equals("BING")) {
			SharedPreferences myPrefs = PreferenceManager
					.getDefaultSharedPreferences(getApplicationContext());
			boolean prefbackgroundMail = myPrefs.getBoolean(
					getText(R.string.direct_email_key).toString(), true);

			if (!bingDetails.getBingId().equals("-8888")) {
				if (!prefbackgroundMail) {
					sendEmailIntent(bingDetails, "Back");
				} else {
					try {
						sendMailAuto(bingDetails, "Back");
					} catch (Exception e) {
						e.printStackTrace();
						Toast.makeText(getApplicationContext(), e.toString(),
								Toast.LENGTH_SHORT).show();
					}

				}
			}
		} else {
			Toast.makeText(getApplicationContext(),
					"Please swipeto the left screen to back bings",
					Toast.LENGTH_SHORT).show();
		}
	}

	private void backAllBings() {
		int backCount = 0;
		if (arrBingList.size() > 0) {
			for (int i = 0; i < arrBingList.size(); i++) {
				try {
					backBing(arrBingList.get(i));
					backCount++;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (view.equals("BING")) {
				if (backCount == 0) {
					Toast.makeText(getApplicationContext(),
							"No bings have been backed.", Toast.LENGTH_SHORT)
							.show();
				} else if (backCount == 1) {
					Toast.makeText(getApplicationContext(),
							"1 bing is being backed.", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(getApplicationContext(),
							backCount + " bings are being backed.",
							Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			if (view.equals("BING"))
				Toast.makeText(getApplicationContext(),
						"No bings have been selected.", Toast.LENGTH_SHORT)
						.show();
		}

	}

	private void deleteAllBings() {
		int delCount = 0;
		ArrayList<BackItSMSDataBean> tempList = new ArrayList<BackItSMSDataBean>();
		tempList.addAll(arrBingList);
		if (tempList.size() > 0) {
			for (int i = 0; i < tempList.size(); i++) {
				delCount += deleteBing(tempList.get(i));
				deleteSMS(tempList.get(i));
			}
			if (delCount == 0) {
				Toast.makeText(getApplicationContext(),
						"No messages have been deleted.", Toast.LENGTH_SHORT)
						.show();
			} else if (delCount == 1) {
				Toast.makeText(getApplicationContext(),
						"1 message has been deleted.", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(getApplicationContext(),
						delCount + " messages have been deleted.",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getApplicationContext(),
					"No messages are present in the list.", Toast.LENGTH_SHORT)
					.show();
		}
	}

	private void backSelectedBing() {
		int backCount = 0;
		if (selBingList.size() > 0) {
			for (int i = 0; i < selBingList.size(); i++) {
				backBing(selBingList.get(i));
				backCount++;
			}
			if (view.equals("BING")) {
				if (backCount == 0) {
					Toast.makeText(getApplicationContext(),
							"No bings have been backed.", Toast.LENGTH_SHORT)
							.show();
				} else if (backCount == 1) {
					Toast.makeText(getApplicationContext(),
							"1 bing is being backed.", Toast.LENGTH_SHORT)
							.show();
				} else {
					Toast.makeText(getApplicationContext(),
							backCount + " bings are being backed.",
							Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			if (view.equals("BING"))
				Toast.makeText(getApplicationContext(),
						"No bings have been selected.", Toast.LENGTH_SHORT)
						.show();
		}
	}

	private void deleteSelected() {
		int delCount = 0;
		ArrayList<BackItSMSDataBean> tempList = new ArrayList<BackItSMSDataBean>();
		tempList.addAll(selBingList);

		if (tempList.size() > 0) {
			for (int i = 0; i < tempList.size(); i++) {
				delCount += deleteBing(tempList.get(i));
				deleteSMS(tempList.get(i));
			}
			if (delCount == 0) {
				Toast.makeText(getApplicationContext(),
						"No messages have been deleted.", Toast.LENGTH_SHORT)
						.show();
			} else if (delCount == 1) {
				Toast.makeText(getApplicationContext(),
						"1 message has been deleted.", Toast.LENGTH_SHORT)
						.show();
			} else {
				Toast.makeText(getApplicationContext(),
						delCount + " messages have been deleted.",
						Toast.LENGTH_SHORT).show();
			}
		} else {
			Toast.makeText(getApplicationContext(),
					"No messages have been selected.", Toast.LENGTH_SHORT)
					.show();
		}

	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	@Override
	public void onSwipe(int direction) {
		switch (direction) {
		case SimpleGestureFilter.SWIPE_RIGHT:
			arrBingList.clear();
			view = "BING";
			refreshListView();
			break;
		case SimpleGestureFilter.SWIPE_LEFT:
			arrBingList.clear();
			view = "ALERT";
			refreshListView();
			break;
		}
	}

	@Override
	public void onDoubleTap() {
	}

	private void getAlertFromDB() {
		String strWhere = BackItSMSInbox.BINGID + " = \"-8888\"";
		Cursor c = getContentResolver().query(
				BackItSMSInbox.CONTENT_URI,
				new String[] { BackItSMSInbox._ID, BackItSMSInbox.BINGID,
						BackItSMSInbox.RECEPIENT, BackItSMSInbox.MESSAGE,
						BackItSMSInbox._COUNT, BackItSMSInbox.DATE }, strWhere,
				null, null);
		BackItSMSDataBean smsDataBean = null;
		try {
			if (c != null && c.getCount() > 0) {
				c.moveToFirst();
				do {
					smsDataBean = new BackItSMSDataBean();
					smsDataBean.setId(c.getInt(0));
					smsDataBean.setBingId(c.getString(1));
					smsDataBean.setRecepient(c.getString(2));
					smsDataBean.setMessage(c.getString(3));
					smsDataBean.setCount(c.getInt(4));
					smsDataBean.setDate(c.getString(5));
					arrBingList.add(smsDataBean);
				} while (c.moveToNext());
			} else {
				// checkEmptyList();
			}
		} catch (Exception e) {

		} finally {
			c.close();
		}
	}

	private int addItemsToSelection() {
		int count = this.list.getAdapter().getCount();
		int selCount = 0;

		selBingList.clear();
		for (int i = 0; i < count; i++) {
			if (this.list.isItemChecked(i)) {
				Object data = this.list.getItemAtPosition(i);
				selBingList.add((BackItSMSDataBean) data);
				selCount++;
			}
		}
		return selCount;
	}
}